package com.example.demo.concurrent.AtomicTest.MyUnSafe;

import sun.misc.Unsafe;

import java.lang.reflect.Field;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-03-14
 * Time: 23:17
 */
public class UnSafeTest1 {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        //通过反射获取到UnSafe对象
        Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafe.setAccessible(true);//允许获取私有变量-->通过反射
        //得到unsafe中的对象
        Unsafe unsafe = (Unsafe) theUnsafe.get(null);
        long nameOffset = unsafe.objectFieldOffset(BBQ.class.getDeclaredField("name"));
        long ageOffset = unsafe.objectFieldOffset(BBQ.class.getDeclaredField("age"));
        BBQ bbq = new BBQ();
        System.out.println(unsafe.compareAndSwapObject(bbq,nameOffset,null,"李四"));
        System.out.println(unsafe.compareAndSwapInt(bbq,ageOffset,0,11));
    }

}

class BBQ{
    private String name;
    private int age;
}
